package com.zzt.upload;

import org.apache.commons.io.FileUtils;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

public class UploadFile {
    //获取图片上传路径
    public static String uploadSaveImage(MultipartFile file,String path){
        //上传图片路径
        String imagePath = "";
        if (file != null){
            //获取文件名（图片名称）以及后缀名 如：微信图片_20190905152041.jpg
            String fileName = file.getOriginalFilename();
            //获取时间（作为存储图片的文件名）
            DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            String nowDate = dtf.format(LocalDateTime.now());
            //获取时间的毫秒数（作为新文件名）
            String timeInMillis = String.valueOf(Calendar.getInstance().getTimeInMillis());
            //获取后缀名
            String fileType = "." + fileName.split("\\.")[1];
            //保存文件的完整路径
            String allPath = path+ "ueditor/jsp/upload/image" + "\\" + nowDate + "\\";
            File saveFile = new File(allPath + "\\" + timeInMillis + fileType);
            try {
//                file.transferTo(saveFile);
                FileUtils.copyInputStreamToFile(file.getInputStream(), saveFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
            imagePath = "/ueditor/jsp/upload/image/" + nowDate + "/" + timeInMillis + fileType;
            System.out.println( imagePath );
        }
        return imagePath;
    }

    //获取视频上传
    public static Map<String,Object> uploadSaveVideo(MultipartFile file, String path){
        Map<String,Object> map = new HashMap<>();
        String videoPath = "";
        if(file != null){
            String fileName = file.getOriginalFilename();
            String fileType = "." + fileName.split("\\.")[1];
            DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            String nowDate = dtf.format(LocalDateTime.now());
            String timeInMillis = String.valueOf(Calendar.getInstance().getTimeInMillis());

            videoPath = path + "ueditor/jsp/upload/video/" + nowDate + "\\" + timeInMillis + fileType;
            File saveFile = new File(videoPath);
            try {
                file.transferTo(saveFile);
                String videoImagePath = "";
                if(!file.getContentType().contains("audio")){
                    videoImagePath = fetchFrame(videoPath,path);//获取视频第一帧
                }
                videoPath = "ueditor/jsp/upload/video/" + nowDate + "/" + timeInMillis + fileType;
                map.put("videoPath",videoPath);//视频路径
                map.put("videoImage",videoImagePath);//视频第一帧路径
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return map;
    }

    //获取视频第一帧
    public static String fetchFrame(String videoPath,String path){
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String nowDate = dtf.format(LocalDateTime.now());
        String timeInMillis = String.valueOf(Calendar.getInstance().getTimeInMillis());
        //存放图片第一帧的路径
        String videoFetchImagePath = path + "ueditor/jsp/upload/video/" + nowDate;

        //创建视频存放路径
        File file = new File(videoFetchImagePath);
        if(!file.exists()) {
            file.mkdirs();
        }

        FFmpegFrameGrabber ffg = null;
        try {
            File imageFile = new File(videoFetchImagePath + "\\" + timeInMillis + ".jpg");
            ffg = new FFmpegFrameGrabber(videoPath);
            ffg.start();
            long videoLength = ffg.getLengthInFrames();
            int num = 0;
            Frame frame = null;
            while (num < videoLength){
                frame = ffg.grabFrame();
                //过滤前五帧，避免出现全黑的图片
                if (num > 48 && frame.image != null){
                    break;
                }
                num ++;
            }
            int oWidth = frame.imageWidth;
            int oHeight = frame.imageHeight;

            //对截取的帧进行等比例缩略
            int width = 360;
            int height = (int)(((double)width/oWidth)*oHeight);
            Java2DFrameConverter converter = new Java2DFrameConverter();
            BufferedImage fecthedImage = converter.getBufferedImage(frame);
            BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
            bi.getGraphics().drawImage(fecthedImage.getScaledInstance(width, height, Image.SCALE_SMOOTH),
                    0, 0, null);
            ffg.stop();
            ImageIO.write(bi,"jpg",imageFile);
            videoFetchImagePath = "/ueditor/jsp/upload/video/" + nowDate + "/" + timeInMillis + ".jpg";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return videoFetchImagePath;
    }

}
